package activity

import activity.adapter.ScanAdapter
import activity.adapter.ScanPastDueAdapter
import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.github.ybq.android.spinkit.SpinKitView
import com.hontech.pizzav2.R
import event.InventoryChangedEvent
import event.PastDueWaresChanged
import event.ReplenishErrorEvent
import event.motor.MotorCode
import event.motor.ScanStatusChangedEvent
import manager.*
import mvc.model.inventory.ScanModel
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import popup.HintDialog
import task.RefreshWaresCargoTask
import task.ReplenishTask

class ScanActivity : AppCompatActivity() {

    companion object {
        var isShow = false
    }

    private val mRecyclerViewScan: RecyclerView by lazy {
        findViewById<RecyclerView>(R.id.id_scan_recycler_view_scan)
    }
    private val mRecyclerViewReplErr: RecyclerView by lazy {
        findViewById<RecyclerView>(R.id.id_scan_recycler_view_repl_error)
    }
    private val mRecyclerViewReplSucc: RecyclerView by lazy {
        findViewById<RecyclerView>(R.id.id_scan_recycler_view_repl_succ)
    }

    private val mButtonQuit: Button by lazy { findViewById<Button>(R.id.id_scan_button_quit) }

    private val mButtonCommit: Button by lazy { findViewById<Button>(R.id.id_scan_button_commit) }

    private val mProgressBar: SpinKitView by lazy { findViewById<SpinKitView>(R.id.id_scan_progress_bar) }

    private var mIsScanFinish = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scan)
        initUi()
    }

    private fun initUi() {
        mButtonCommit.setOnClickListener(::onClickCommit)
        mButtonQuit.setOnClickListener(::onClickQuit)
        mIsScanFinish = false
        mButtonCommit.visibility = View.GONE
        mProgressBar.visibility = View.GONE

        ReplenishManager.clearAll()

        mRecyclerViewScan.layoutManager = LinearLayoutManager(
            this, LinearLayoutManager.VERTICAL,
            false
        )

        mRecyclerViewScan.adapter = ScanAdapter(ReplenishManager.getScanModels())

        mRecyclerViewReplErr.layoutManager = LinearLayoutManager(
            this, LinearLayoutManager.VERTICAL,
            false
        )

        mRecyclerViewReplSucc.layoutManager = LinearLayoutManager(
            this,
            LinearLayoutManager.VERTICAL, false
        )
    }

    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
        AppManager.isBusy = false
    }

    override fun onStart() {
        super.onStart()
        AppManager.isBusy = true
        EventBus.getDefault().register(this)

        /**
         * 开始扫描
         */
        DeliveryManager.scan()
    }

    override fun onPause() {
        isShow = false
        super.onPause()
    }

    override fun onResume() {
        isShow = true
        super.onResume()
    }

    private fun showDialog(title: String, content: String) {
        val dialog = HintDialog(title, content, mRecyclerViewReplErr)
        dialog.show()
    }

    private fun onClickCommit(view: View) {
        if (!mIsScanFinish) {
            showDialog(
                "Warning",
                "Please wait for the scan to complete"
            )
            return
        }
        /**
         * 开始补货
         */
        mProgressBar.visibility = View.VISIBLE
        AsyncTask.post(ReplenishTask(ReplenishManager.getScanModels()))
    }

    private fun onClickQuit(view: View) {
        finish()
    }

    /**
     * 补货过程中发生错误
     */
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onReplenishErrorEvent(env: ReplenishErrorEvent) {
        mProgressBar.visibility = View.GONE
        showDialog(
            "Error",
            "Replenishment failed, please check network or server Settings"
        )
    }

    /**
     * 补货返回
     */
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onPastDueWaresChangedEvent(env: PastDueWaresChanged) {
        /**
         * 必须要先扫描完成
         */
        if (!mIsScanFinish) {
            return
        }

        /**
         * 开始获取库存
         */
        val adapter = ScanPastDueAdapter(env.pastDues)
        mRecyclerViewReplErr.adapter = adapter
        AsyncTask.post(RefreshWaresCargoTask())
    }

    /**
     * 获取库存返回
     */
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onInventoryChangedEvent(env: InventoryChangedEvent) {
        /**
         * 必须要先扫描完成
         */
        if (!mIsScanFinish) {
            return
        }

        val goodsTypes = WaresManager.toGoodsTypes()
        val adapter = ScanPastDueAdapter(goodsTypes)
        mRecyclerViewReplSucc.adapter = adapter

        mButtonCommit.visibility = View.GONE
        mProgressBar.visibility = View.GONE
    }

    /**
     * 扫描返回
     */
    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onScanChangedEvent(env: ScanStatusChangedEvent) {
        if (env.state == MotorCode.SCAN_FINISH) {
            mButtonCommit.visibility = View.VISIBLE
            mIsScanFinish = true
            return
        }
        ReplenishManager.onScaned(ScanModel.withScanEvent(env))
        val adapter = mRecyclerViewScan.adapter!!
        adapter.notifyDataSetChanged()
        if (adapter.itemCount > 0) {
            mRecyclerViewScan.scrollToPosition(adapter.itemCount - 1)
        }
    }
}









